package com.wx.filter;

import cn.hutool.json.JSONUtil;
import com.wx.common.SecurityUser;
import com.wx.constants.Constants;
import com.wx.constants.RedisKeyPrefix;
import com.wx.service.RedisService;
import com.wx.utils.SpringContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Title:      CustomerAuthenticationFilter. </p>
 * <p>Description TODO </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:    医百科技有限公司 </p>
 *
 * @author         <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since      2020/9/20 23:07
 */
public class CustomerAuthenticationFilter extends BasicAuthenticationFilter {

    @Resource
    private RedisService redisService;

    public CustomerAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        //当token为空或格式错误时 直接放行
        if (header == null || !header.startsWith(Constants.BEARER_AUTHENTICATION)) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(header);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request, response);
    }


    private UsernamePasswordAuthenticationToken getAuthentication(String header) {
        String token = header.replace(Constants.BEARER_AUTHENTICATION, "");
        if(redisService == null){
            redisService = SpringContextHolder.getBean("redisService");
        }
        Object obj = redisService.get(RedisKeyPrefix.ONLINEUSER+token);
        if (obj != null) {
            SecurityUser securityUser = JSONUtil.toBean(obj.toString(), SecurityUser.class);
            return new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
        }
        return null;
    }

}
